package com.example.ymm.modules1.service.impl.sys;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.modules1.entity.my.sys.DdEventLog;
import com.example.ymm.modules1.entity.my.user.DbChatGroup;
import com.example.ymm.modules1.entity.my.user.DbChatGroupUser;
import com.example.ymm.modules1.entity.my.user.DbDept;
import com.example.ymm.modules1.entity.my.user.DbUser;
import com.example.ymm.modules1.mapper.my.sys.DdEventLogMapper;
import com.example.ymm.modules1.service.dd.DdDeptInfoService;
import com.example.ymm.modules1.service.dd.DdUserServer;
import com.example.ymm.modules1.service.dto.DdEventLogQueryCriteria;
import com.example.ymm.modules1.service.sys.DdEventLogService;
import com.example.ymm.modules1.service.user.*;
import com.example.ymm.util.DateKit;
import com.example.ymm.util.QueryHelpPlus;
import com.example.ymm.util.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
@Slf4j
public class DdEventLogServiceImpl extends BaseServiceImpl<DdEventLogMapper, DdEventLog> implements DdEventLogService {

    @Autowired
    DbDeptService dbDeptService;
    @Autowired
    DdDeptInfoService deptInfoService;
    @Autowired
    DbUserService dbUserService;
    @Autowired
    DdUserServer ddUserServer;
    @Autowired
    DbDeptUserService dbDeptUserService;
    @Autowired
    DbChatGroupUserService dbChatGroupUserService;
    @Autowired
    DbChatGroupService dbChatGroupService;


    public List<DdEventLog> queryAll(DdEventLogQueryCriteria criteria) {
        List<DdEventLog> result =baseMapper.selectList(QueryHelpPlus.getPredicate(DdEventLog.class, criteria));
        return result;
    }

    //处理钉钉事件
    @Override
    public void operatorAllDingdingEventLog(String eventTypeStr) {
        DdEventLogQueryCriteria criteria=new DdEventLogQueryCriteria();
        criteria.setIsFinish(0);
        if(UtilValidate.isNotEmpty(eventTypeStr)){
            criteria.setEventType(eventTypeStr);
        }
        List<DdEventLog> ddEventLogs = queryAll(criteria);
        for(DdEventLog eventLog : ddEventLogs){
            try {
                String eventType = eventLog.getEventType();
                switch (eventType){
                    case "user_leave_org"://员工离职
                        user_leave_org_fn(eventLog);
                        break;
                    case "user_add_org"://新增
                    case "user_modify_org"://修改
                        user_add_org(eventLog);
                        break;
                    case "org_dept_modify"://部门修改
                    case "org_dept_create"://部门新增
                        org_dept_modify(eventLog);
                        break;
                    case "org_dept_remove"://部门删除
                        org_dept_remove(eventLog);
                        break;
                     //入群
                    case "chat_add_member":
                        chat_add_member(eventLog);
                        break;
                     //用户主动退群
                    case "chat_quit":
                        chat_quit(eventLog);
                        break;

                }

            }catch (Exception e){
                log.error(e.getMessage(),e);
            }
        }

    }


    //处理员工离职
    void  user_leave_org_fn(DdEventLog eventLog){
        log.info("--员工离职");
        String data = eventLog.getData();
        JSONObject json= JSON.parseObject(data);
        JSONArray userIdArr = json.getJSONArray("userId");
        for(int a=0;a<userIdArr.size();a++){
            String userId = userIdArr.getString(a);
            // 处理用户离职开始---
            DbUser user = dbUserService.getById(userId);
            if(UtilValidate.isNotEmpty(user)){
                user.setState(0);
                if(json.containsKey("timeStamp")){
                    Date date = new Date(json.getLong("timeStamp"));
                    String s = DateKit.dateFormat(date);
                    user.setRemark("该员工在"+s+"时已离职");

                }
                dbUserService.saveOrUpdate(user);
            }

            //移除部门人员信息

            dbDeptUserService.removeByUserId(userId);

        }
        eventLog.setIsFinish(1);//标记完成
        saveOrUpdate(eventLog);
    }

    //处理部门修改
    void org_dept_modify(DdEventLog eventLog){
        String data = eventLog.getData();
        JSONObject json= JSON.parseObject(data);
        JSONArray deptIdArr = json.getJSONArray("deptId");
        for(int a=0;a<deptIdArr.size();a++){
            String deptId = deptIdArr.getString(a);
            // 部门信息
            JSONObject byDeptJson = deptInfoService.getByDeptId(deptId);
            DbDept dept = dbDeptService.getById(deptId);
            dept.setName(byDeptJson.getString("name"));
            dept.setParentId(byDeptJson.getString("parent_id"));
            dept.setSort(byDeptJson.getInteger("order"));
            //获取主管
            JSONArray manager_list = byDeptJson.getJSONArray("dept_manager_userid_list");
            if(UtilValidate.isNotEmpty(manager_list)){
                String userId = manager_list.getString(0);
                DbUser user = dbUserService.getById(userId);
                dept.setManageUserId(userId);
                if(UtilValidate.isNotEmpty(user)){
                    dept.setManageUserName(user.getUserName());
                }
                dbDeptService.saveOrUpdate(dept);
            }

        }
        eventLog.setIsFinish(1);//标记完成
        saveOrUpdate(eventLog);
    }



    //部门删除
    void org_dept_remove(DdEventLog eventLog){
        String data = eventLog.getData();
        JSONObject json= JSON.parseObject(data);
        JSONArray deptIdArr = json.getJSONArray("deptId");
        for(int a=0;a<deptIdArr.size();a++) {
            String deptId = deptIdArr.getString(a);
            dbDeptService.removeById(deptId);
            log.info("--部门删除"+deptId);
        }
        eventLog.setIsFinish(1);//标记完成
        saveOrUpdate(eventLog);
    }


    //人员增加
    /**
     https://open.dingtalk.com/document/orgapp/address-book-user-change-stream
     */

    void user_add_org(DdEventLog eventLog){
        String data = eventLog.getData();
        JSONObject json= JSON.parseObject(data);
        JSONArray userIdArr = json.getJSONArray("userId");
        for(int a=0;a<userIdArr.size();a++) {
            String userId = userIdArr.getString(a);
            JSONObject userInfo = ddUserServer.getUserInfoByUserId(userId);
            if(UtilValidate.isNotEmpty(userInfo)){
                dbUserService.addUser(userInfo);
            }
        }

        eventLog.setIsFinish(1);//标记完成
        saveOrUpdate(eventLog);

    }

    //群会话主动退群
    void chat_quit(DdEventLog eventLog){
        String data = eventLog.getData();
        JSONObject json= JSON.parseObject(data);
        String openConversationId=json.getString("openConversationId");
        String userId= json.getString("operator");
        LambdaQueryWrapper<DbChatGroupUser> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DbChatGroupUser::getUserId,userId);
        lambdaQueryWrapper.eq(DbChatGroupUser::getOpenConversationId,openConversationId);
        dbChatGroupUserService.remove(lambdaQueryWrapper);
        eventLog.setIsFinish(1);//标记完成
        saveOrUpdate(eventLog);

    }

    void chat_add_member(DdEventLog eventLog){
        String data = eventLog.getData();
        JSONObject json= JSON.parseObject(data);
        String openConversationId=json.getString("openConversationId");
        DbChatGroup chatGroup = dbChatGroupService.getById(openConversationId);
        if(UtilValidate.isNotEmpty(chatGroup)){
            JSONArray userIdArr = json.getJSONArray("userId");
            List<String> userIdLists=new ArrayList<>();
            for(int a=0;a<userIdArr.size();a++) {
                String userId = userIdArr.getString(a);
                userIdLists.add(userId);
            }
            String userIds=String.join(",",userIdLists);
            dbChatGroupUserService.addGroupUser(openConversationId,userIds);
            eventLog.setIsFinish(1);//标记完成
            saveOrUpdate(eventLog);
        }
    }

}
